package com.example.recordingpen_datacollection.Utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Base64;

public class EncryptionUtils {
   

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String AES_KEY = "mySecreAESKey357"; // 16 bytes key for AES
    private static final String AES_IV = "myInitiionVector"; // 16 bytes IV for AES

    static {
   
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String encrypt(String plaintext) {
   
        try {
   
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
   
            e.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String ciphertext) {
   
        try {
   
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            SecretKeySpec keySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] encryptedBytes = Base64.getDecoder().decode(ciphertext);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
   
            e.printStackTrace();
            return null;
        }
    }
}